package filter;

import static org.hamcrest.CoreMatchers.nullValue;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginFilter implements Filter{

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// TODO 自动生成的方法存根
		//强制类型转换
		HttpServletRequest  req=(HttpServletRequest)request;
		HttpServletResponse  res=(HttpServletResponse)response;
		
		//String uri=req.getRequestURI();
		//如果用户转向的不是login.jsp页面，获取会话变量username,判断是否为空；为空则表示尚未登录，转向登录页面；否则正常响应用户请求
		if(req.getSession().getAttribute("username")==null) {
			String username=null,password=null;
			//获取请求中所有cookie对象数组
			Cookie[] cookies=req.getCookies();
			if(cookies!=null) {
				for (Cookie  cookie:cookies) {
					//查找前面存储的cookie，名字是meeting.username,meeting.password,将cookie值分别赋给username,password变量
					if(cookie.getName().equals("meeting.username"))
						username=cookie.getValue();
					if(cookie.getName().equals("meeting.password"))
						password=cookie.getValue();
				}
					
			}
			if((username!=null)&&(password!=null))
			{
				//获取到免登录的cookie值，则跳过该过滤器，向下传递
				chain.doFilter(request, response);
			}
			else {
			
			//加绝对路径，防止404错误
			res.sendRedirect(req.getContextPath()+"/login.jsp");
		}
		}
		else {
			chain.doFilter(request,response);
		}
		
	}

}
